#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2014 OPS, Qunar Inc. (qunar.com)
#
# Author: tingfang.bao <tingfang.bao@qunar.com>
# DateTime: 15-3-6 下午6:26
from flask import Flask, g, abort, Response, session
from flask.views import MethodView

app = Flask(__name__)
app.secret_key = 'baotingfang'


def user_required(f):
    def decorator(*args, **kwargs):
        if 'username' not in session:
            abort(401)
        return f(*args, **kwargs)

    return decorator


# 注意http方法必须是小写
# noinspection PyMethodMayBeStatic
class UserAPI(MethodView):
    # 所有的方法都必须要登陆，如果是单个方法的话，可以将装饰器单独作用在方法上
    # decorators = [user_required]

    def get(self):
        return 'GET METHOD!'

    def post(self):
        # 传入的参数，可以使用request对象获取
        return 'POST METHOD!'

    def delete(self):
        return 'DELETE METHOD!'

    def put(self):
        return 'PUT METHOD!'

    def options(self):
        return 'OPTIONS METHOD!'

    def head(self):
        return 'HEAD METHOD!'

    def patch(self):
        return 'PATCH METHOD!'


view = user_required(UserAPI.as_view('users'))
# 这是需要验证的
app.add_url_rule('/v1/sec_users/', view_func=view)

app.add_url_rule('/v1/users/', view_func=UserAPI.as_view('users'))


@app.route('/login')
def login():
    session['username'] = 'baotingfang'
    return Response()


@app.route('/logout')
def logout():
    session.clear()
    return Response()


if __name__ == '__main__':
    app.debug = True
    app.run(host='0.0.0.0', port=8080)